using System;
using System.ComponentModel;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using Devv.Core.Crypto;
using Devv.Core.Erroo;

namespace Devv.Threeter.Twitter
{
	[Serializable]
	public class Accounts : BindingList<Account>
	{
		#region Variables

		public readonly String XmlPath = Application.UserAppDataPath + "\\Accounts.xml";
		public readonly String XmlSchema = "<?xml version=\"1.0\"?>" + Environment.NewLine + "<Accounts></Accounts>";

		#endregion

		#region Load

		public void Load()
		{
			Clear();

			XmlDocument xml = new XmlDocument();

			try
			{
				if (File.Exists(XmlPath))
				{
					xml.Load(XmlPath);
				}
				else
				{
					xml.LoadXml(XmlSchema);
				}

				XmlNodeList nodes = xml.DocumentElement.SelectNodes("//Account");

				foreach (XmlNode node in nodes)
				{
					String username = node.SelectSingleNode("Username").InnerText;
					String token = node.SelectSingleNode("Token").InnerText;
					String secret = node.SelectSingleNode("Secret").InnerText;

					if (username.Length > 15)
					{
						username = Cipher.AESDecrypt(username);
						token = Cipher.AESDecrypt(token);
						secret = Cipher.AESDecrypt(secret);
					}

					Add(new Account(username, token, secret));
				}
			}
			catch (Exception ex)
			{
				ErrorHandler.Handle(ex, "Could not load your saved Twitter accounts.");
			}
		}

		#endregion

		#region Save

		public void Save()
		{
			XmlDocument xml = new XmlDocument();

			xml.LoadXml(XmlSchema);

			foreach (Account ac in this)
			{
				XmlElement node = xml.CreateElement("Account");

				XmlElement username = xml.CreateElement("Username");
				XmlElement token = xml.CreateElement("Token");
				XmlElement secret = xml.CreateElement("Secret");

				username.InnerText = Cipher.AESEncrypt(ac.Username);
				token.InnerText = Cipher.AESEncrypt(ac.Token);
				secret.InnerText = Cipher.AESEncrypt(ac.Secret);

				node.AppendChild(username);
				node.AppendChild(token);
				node.AppendChild(secret);

				xml.DocumentElement.AppendChild(node);
			}

			try
			{
				xml.Save(XmlPath);
			}
			catch (Exception ex)
			{
				ErrorHandler.Handle(ex, "Could not save your Twitter accounts to the hard disk.");
			}
		}

		#endregion

		#region Helper

		public Account Find(String username)
		{
			username = username.ToLower();

			foreach (Account item in this)
			{
				if (item.Username.ToLower() == username)
				{
					return item;
				}
			}

			return null;
		}

		public void Remove(String username)
		{
			for (Int32 i = 0; i < Count; i++)
			{
				if (this[i].Username == username)
				{
					RemoveAt(i);
					i = Count;
				}
			}
		}

		#endregion
	}
}
